using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices; 
using System.Data;

namespace HexLib.Url
{
	/// <summary>
	/// Descrizione di riepilogo per WebHttpQuestioner.
	/// </summary>
	public class WebHttpQuestioner
	{
        private static bool generateLogOnDebug = false;
		private static CookieContainer cookieCont = new CookieContainer();
		private static HttpWebRequest wrInfoCam = null;
		private static HttpWebResponse resp = null;
		private static bool useProxy = false;
		private static string serverProxy = "";
		private static string portProxy = "";
		private static bool useProxyLogin = false;
		private static string userNameProxy = "";
		private static string passwordProxy = "";
		private static string domainProxy = "";
		private static int numFile = 0;

        public static bool GenerateLogOnDebug
        {
            set { generateLogOnDebug = value; }
            get { return generateLogOnDebug; }
        }

        public static CookieContainer Cookies
        {
            get { return cookieCont; }
        }

		public static bool UseProxy
		{
			get
			{
				return useProxy;
			}
			set
			{
				useProxy=value;
			}
		}

		public static bool UseProxyLogin
		{
			get
			{
				return useProxyLogin;
			}
			set
			{
				useProxyLogin=value;
			}
		}

		public static string ServerProxy
		{
			get
			{
				return serverProxy;
			}
			set
			{
				serverProxy=value;
			}
		}

		public static string PortProxy
		{
			get
			{
				return portProxy;
			}
			set
			{
				portProxy=value;
			}
		}

		public static string UserNameProxy
		{
			get
			{
				return userNameProxy;
			}
			set
			{
				userNameProxy=value;
			}
		}

		public static string PasswordProxy
		{
			get
			{
				return passwordProxy;
			}
			set
			{
				passwordProxy=value;
			}
		}

		public static string DomainProxy
		{
			get
			{
				return domainProxy;
			}
			set
			{
				domainProxy=value;
			}
		}

		public static string GetHtmlWithMethodPost(string url,byte[] postDataBytes)
		{
			wrInfoCam =(HttpWebRequest) HttpWebRequest.Create(url);
			wrInfoCam.Method="POST";
			wrInfoCam.ContentType = "application/x-www-form-urlencoded";

			if(useProxy)
			{
				string proxyUrl=string.Format("http://{0}:{1}",serverProxy,portProxy);
				//Definizione credenziali
				WebProxy proxy=new WebProxy(proxyUrl,true);
				if(useProxyLogin)
				{
					NetworkCredential netcred=new NetworkCredential(userNameProxy,passwordProxy,domainProxy);

					CredentialCache myCache = new CredentialCache();
					myCache.Add(new Uri(proxyUrl),"Basic",netcred);
					proxy.Credentials=netcred;
				}

				wrInfoCam.Proxy = proxy;
			}

			wrInfoCam.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-powerpoint, application/vnd.ms-excel, */*";
			wrInfoCam.CookieContainer = cookieCont;
			wrInfoCam.KeepAlive = true;
			wrInfoCam.AllowAutoRedirect = true;

			wrInfoCam.ContentLength = postDataBytes.Length;

			Stream postDataStream = wrInfoCam.GetRequestStream();
			postDataStream.Write(postDataBytes, 0, postDataBytes.Length);
			postDataStream.Close();

			resp=(HttpWebResponse) (wrInfoCam.GetResponse());

			Stream streamResponse = null;
			StreamReader streamRead = null;
			string html = "";
			try
			{
				streamResponse=resp.GetResponseStream();
				streamRead = new StreamReader(streamResponse);
				html=streamRead.ReadToEnd();
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
			finally
			{
				if(streamRead!=null)
					streamRead.Close();
				if(streamResponse!=null)
					streamResponse.Close();				
			}

            if (GenerateLogOnDebug)
            {
                // Print the properties of each cookie.
                foreach (Cookie cook in resp.Cookies)
                {
                    Console.WriteLine("Cookie:");
                    Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
                    Console.WriteLine("Domain: {0}", cook.Domain);
                    Console.WriteLine("Path: {0}", cook.Path);
                    Console.WriteLine("Port: {0}", cook.Port);
                    Console.WriteLine("Secure: {0}", cook.Secure);

                    Console.WriteLine("When issued: {0}", cook.TimeStamp);
                    Console.WriteLine("Expires: {0} (expired? {1})",
                        cook.Expires, cook.Expired);
                    Console.WriteLine("Don't save: {0}", cook.Discard);
                    Console.WriteLine("Comment: {0}", cook.Comment);
                    Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
                    Console.WriteLine("Version: RFC {0}", cook.Version == 1 ? "2109" : "2965");

                    // Show the string representation of the cookie.
                    Console.WriteLine("String: {0}", cook.ToString());
                }

                StreamWriter sw = new StreamWriter(string.Format(".\\prova{0}.html", ++numFile));
                sw.Write(html);
                sw.Flush();
                sw.Close();
            }
			return html;
		}

		public static string GetHtml(string url)
		{
			try
			{
				wrInfoCam =(HttpWebRequest) HttpWebRequest.Create(url);
				wrInfoCam.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-powerpoint, application/vnd.ms-excel, */*";
				wrInfoCam.CookieContainer = cookieCont;
				wrInfoCam.KeepAlive = true;
				wrInfoCam.AllowAutoRedirect = true;

				if(useProxy)
				{
					string proxyUrl=string.Format("http://{0}:{1}",serverProxy,portProxy);
					//Definizione credenziali
					WebProxy proxy=new WebProxy(proxyUrl,true);
					if(useProxyLogin)
					{
						NetworkCredential netcred=new NetworkCredential(userNameProxy,passwordProxy,domainProxy);

						CredentialCache myCache = new CredentialCache();
						myCache.Add(new Uri(proxyUrl),"Basic",netcred);
						proxy.Credentials=netcred;
					}

					wrInfoCam.Proxy = proxy;
				}

				resp=(HttpWebResponse) (wrInfoCam.GetResponse());

				Stream streamResponse = null;
				StreamReader streamRead = null;
				string html = "";
				try
				{
					streamResponse=resp.GetResponseStream();
					streamRead = new StreamReader(streamResponse);
					html=streamRead.ReadToEnd();
				}
				catch(Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
				finally
				{
					if(streamResponse!=null)
						streamResponse.Close();
					if(streamRead!=null)
						streamRead.Close();
				}
                if (GenerateLogOnDebug)
                {
                    // Print the properties of each cookie.
                    foreach (Cookie cook in resp.Cookies)
                    {
                        Console.WriteLine("Cookie:");
                        Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
                        Console.WriteLine("Domain: {0}", cook.Domain);
                        Console.WriteLine("Path: {0}", cook.Path);
                        Console.WriteLine("Port: {0}", cook.Port);
                        Console.WriteLine("Secure: {0}", cook.Secure);

                        Console.WriteLine("When issued: {0}", cook.TimeStamp);
                        Console.WriteLine("Expires: {0} (expired? {1})",
                            cook.Expires, cook.Expired);
                        Console.WriteLine("Don't save: {0}", cook.Discard);
                        Console.WriteLine("Comment: {0}", cook.Comment);
                        Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
                        Console.WriteLine("Version: RFC {0}", cook.Version == 1 ? "2109" : "2965");

                        // Show the string representation of the cookie.
                        Console.WriteLine("String: {0}", cook.ToString());
                    }

                    StreamWriter sw = new StreamWriter(string.Format(".\\prova{0}.html", ++numFile));
                    sw.Write(html);
                    sw.Flush();
                    sw.Close();
                }
				return html;
			}
			catch
			{
				return null;
			}
		}
	}
}
